var count=0;
var sum=0;        //数据库中获取
var update1=0;
var pyth = new Array();
var totalNum=0;
var control=false;
var obj;
window.onload=function(){

    //动态生成下拉列表
    function getJson(){
        $.ajax({
            url:'./admin/controller.php',
            type: "POST",
            data:{url:'getSelectNum'},
            async:true,  //异步处理
            success: function(data){
                data=eval('('+data+')');
                var selectOpti = $("#selectOpti");
                selectOpti.empty();
                for(var i=0;i<data.length;i++) {
                    $("#selectOpti").append("<option value=\"1\">类型:"+data[i][0]+",长:"+data[i][1]+",宽:"+data[i][2]+',颜色:'+data[i][3]+"</option>");
                }
            },
        });
    }
    getJson();
    $("#delete").hide();
    var map = new qq.maps.Map(document.getElementById("container"), {
        center: new qq.maps.LatLng(39.916527, 116.397128),      // 地图的中心地理坐标。
        zoom:15,// 地图的中心地理坐标。
        minZoom:15,
        backgroundColor:"#272822",
        draggableCursor:"crosshair",
        mapTypeControl:true,
        mapTypeControlOptions: {
            mapTypeIds: [
                qq.maps.MapTypeId.ROADMAP,
                qq.maps.MapTypeId.HYBRID,
                qq.maps.MapTypeId.SATELLITE
            ],
            position: qq.maps.ControlPosition.TOP_RIGHT
        },
        scaleControl:true,
        scaleControlOptions: {
            position: qq.maps.ControlPosition.BOTTOM_RIGHT
        },
        zoomControl:true,
        zoomControlOptions:{
            position: qq.maps.ControlPosition.RIGHT_BOTTOM
        },
        disableDoubleClickZoom: true,
    });
    //加载已创建覆盖物表中存储的svg
    function getJson2() {
        $.ajax({
            url: "./admin/controller.php",
            type: "POST",
            data:{url:'getTheStore'},
            dataType:'json',
            async:true,
            success: function(data){
				alert(data);
                if(data){
                    //totalNum+=sum;
                    totalNum+=parseInt(data[2]);
                    $("#number6").val(data[2]);
                    sum=parseInt(data[1]);
                    readinto();
                }
            },
            error: function () {
                alert("数据库加载失败");
            },
        });
    }
    getJson2();
    //调用地址解析类
    geocoder = new qq.maps.Geocoder({
        complete : function(result){
            map.setCenter(result.detail.location);
        }
    });
    //根据指定的范围调整地图视野
    //map.fitBounds(latlngbounds);
    var customZoomDiv = document.createElement("div");
    customZoomDiv.style.cssText = "padding:5px;border:2px solid #86acf2;background:#ffffff";
    customZoomDiv.index = 1; //设置在当前布局中的位置
    function update() {
        customZoomDiv.innerHTML = "地图缩放级别：" + map.getZoom();
    }
    qq.maps.event.addDomListener(map, "zoom_changed", update);
    update();

    map.controls[qq.maps.ControlPosition.TOP_CENTER].push(customZoomDiv);

    //根据客户端ip定位地图中心位置
    var cityLocation=null,
    cityLocation=new qq.maps.CityService();
    cityLocation.setComplete(function(result){
    	map.setCenter(result.detail.latLng);
    });
    cityLocation.searchLocalCity();
    var infoWin = new qq.maps.InfoWindow({
        map: map
    });

    //点击确认按钮触发属性修改
    $('#btn1').click(function() {
        count--;
        var lat= pyth[update1].num1;           //经度
        var lng= pyth[update1].num2;
        var tlength = pyth[update1].tlength;      //经度
        var twidth = pyth[update1].twidth;
        var scole1=0;
        var scole2=$("input[name='tnumber4']").val();
        var color=$("#color").css('background-color');
        var sHexColor = RGBToHex(color);
        var type=$('option:selected', '#selectOpti').index()+1;
        createIcon(pyth,map,update1,lat,lng,tlength,twidth,scole1,scole2,sHexColor,type);
        $.ajax({
            type:'POST',
            url:'./admin/changeLoadIcon.php',
            data:{
                url:'updateScole',
                number:update1,
                scole:scole2
            },
            beforeSend:function () {
                //alert("begin");
            },
            error:function()
            {
                alert("未知错误");
            },
            success:function(data)
            {
                //alert(data);
            }
        });
        count++;
    });
    //批量创建
    $("#btn3").click(function(){
        $("#delete").hide();
        var val=$('input[name="number5"]').val();
        var lng=map.getCenter().getLat();
        var lat=map.getCenter().getLng();               //经度
        var color=$("#color2").css('background-color');
        var sHexColor = RGBToHex(color);
        var a=$("#selectOpti option:selected").text();
        var re=a.split(":");
        for(var i=0;i<re.length;i++){
            re[i]=parseFloat(re[i]);
        }
        var tlength = re[2];                 //经度
        var twidth = re[3];
        // var color1=color.colorHex();
        sumcreate(val,lat,lng,tlength,twidth,sHexColor);
        $("#number6").val(totalNum);
    });
    //var tlength = $("input[name='tlength']").val();
    //var twidth = $("input[name='twidth']").val();
    //批量新建       经度  纬度
    function sumcreate(createnum,centerlat,centerlng,tlength,twidth,color){
        if(createnum<=0){
            alert("请输入合法个数");
            return;
        }
        var number=Math.ceil(Math.sqrt(createnum));
        var start=new qq.maps.LatLng(centerlng, centerlat);
        var end=new qq.maps.LatLng(centerlng/1.0+1, centerlat);
        var start2=new qq.maps.LatLng(centerlng, centerlat);
        var end2=new qq.maps.LatLng(centerlng, centerlat/1.0+1);
        var addnum1_1  = 2*tlength / getDistance(start2,end2);        //经度
        var addnum2_1 = 2*twidth / getDistance(start,end);          //纬度
        var lng=centerlat-number/2*addnum1_1;                                      //经度
        var lat=centerlng+number/2*addnum2_1;                                      //纬度
        var j=1;
        for(var i=0;i<createnum;i++){
            pyth[count] = new Object();
            pyth[count].thebool=1;
            pyth[i].polygon=0;
            var type=$('option:selected', '#selectOpti').index()+1;
            createIcon(pyth,map,count,lng,lat,tlength,twidth,0,0,color,type);
            totalNum+=1;
            if(i/100==0){
                setTimeout(function(){
                },100);
            }
            if(j>=number){
                lng=centerlat-number/2*addnum1_1;
                lat+=addnum2_1;
                j=1;
            }else{
                lng+=addnum1_1;
                j++;
            }
            var count2=count;
            $.ajax({
                type:'POST',
                url:'./admin/changeLoadIcon.php',
                data:{
                    url:'saveChange',
                    thetype:pyth[count2].typeof,
                    lng:pyth[count2].num1,
                    lat:pyth[count2].num2,
                    scole:pyth[count2].scole2,
                    isDel:pyth[count2].isDel
                },
                beforeSend:function () {
                    //alert("begin");
                },
                error:function()
                {
                    alert("未知错误");
                },
                success:function(data)
                {
                    //alert(data);
                }
            });

            count++;
        }

        map.setCenter(new qq.maps.LatLng(lat, lng));
    }
    $("#delete").click(function(){
        totalNum--;
        $("#delete").hide();
        deleteIcon(pyth,update1);
        $("#number6").val(totalNum);
        //updateChange
        $.ajax({
            type:'POST',
            url:'./admin/changeLoadIcon.php',
            data:{
                url:'updateChange',
                number:update1,
            },
            beforeSend:function () {
                //alert("begin");
            },
            error:function()
            {
                alert("未知错误");
            },
            success:function(data)
            {
                //alert(data);
            }
        });
        //alert("删除成功");
    });
    //删除某一个坐标的方法
    function deleteIcon(pyth,count){
        $("input[name='tnumber5']").val("--");
        pyth[count].polygon.setMap(null);
        pyth[count].marker.setMap(null);
        pyth[count].isDel=1;
        $("input[name='tlength']").val("--");
        $("input[name='twidth']").val("--");
        $("input[name='tnumber1']").val("--");
        $("input[name='tnumber2']").val("--");
    }
    //select索引改变时
    $("#selectOpti").change(function(){
        var a=$("#selectOpti option:selected").text();
        var sarr=new Array();
        sarr=a.split("#");
        var color="#"+sarr[1];
        $("#color2").css('background-color',color);
    });
    //双击地图触发添加事件
    qq.maps.event.addListener(map,"dblclick",function(event){
        var a=$("#selectOpti option:selected").text();
        var re=a.split(":");
        for(var i=0;i<re.length;i++){
            re[i]=parseFloat(re[i]);
        }
        totalNum+=1;
        pyth[count] = new Object();
        pyth[count].thebool=1;
        pyth[count].polygon=0;
        var lat=event.latLng.getLat();
        var lng=event.latLng.getLng();              //经度
        var tlength = re[2];                 //经度
        var twidth = re[3];
        var scole1=0;
        var scole2=0;
        var color=$("#color2").css('background-color');
        var sHexColor = RGBToHex(color);
        var type=$('option:selected', '#selectOpti').index()+1;
        createIcon(pyth,map,count,lng,lat,tlength,twidth,scole1,scole2,sHexColor,type);
        $("#number6").val(totalNum);
        var count2=count;
        $.ajax({
            type:'POST',
            url:'./admin/changeLoadIcon.php',
            data:{
                url:'saveChange',
                thetype:pyth[count2].typeof,
                lng:pyth[count2].num1,
                lat:pyth[count2].num2,
                scole:pyth[count2].scole2,
                isDel:pyth[count2].isDel
            },
            beforeSend:function () {
                //alert("begin");

            },
            error:function()
            {
                alert("未知错误");
            },
            success:function(data)
            {
                //alert(data);
            }
        });
        //updateAndAdd(pyth,count);
        count++;
    });

    //地图缩放级别改变时触发事件  //document.body.clientWidth
    qq.maps.event.addListener(map,'zoom_changed',function(event){
        if(this.getZoom()==17)
        {
            //获取经纬度范围参数
            var bs = map.getBounds();//获取可视区域
            var bssw = bs.getSouthWest();//可视区域左下角
            var bsne = bs.getNorthEast();//可视区域右上角
            var topLat = bsne.lat;
            var bottomLat = bssw.lat;
            var leftLng = bssw.lng;
            var rightLng = bsne.lng;
            $.ajax({
               type:'POST',
                url:'./admin/changeLoadIcon.php',
                data:{
                  topLat:topLat,bottomLat:bottomLat,leftLng:leftLng,rightLng:rightLng,url:'loadChange'
                },
                success:function(data)
                {
                    if(data){
                        data=eval('('+data+')');
                        for(var i=0;i<data.length;i++){
                            var number=parseInt(data[i][4]);
                            var type=data[i][0];
                            pyth[number].thebool=1;
                            createIcon(pyth,map,number,data[i][5],data[i][6],data[i][1],data[i][2],0,data[i][7],data[i][3],type);
                        }
                    }
                }
            });
        }
        else{
            $('svg').hide();
            $("div[title*='目标图标']").hide();
        }
    });

    //topLatBefore,topLatAfter,bottomLatBefore,bottomLatAfter,leftLngBefore,leftLngAfter,rightLngBefore,rightLngAfter;
    //开始拖拽地图，地图位置改变时
    qq.maps.event.addListener(map,'dragstart',function(){
        //开始拖拽清空图标
        $.ajax({
            type:'POST',
            url:'./admin/adminController.php',
            data:{},
            success:function() {
                for(var i=0;i<count;i++)
                {
                    if(pyth[i].polygon)
                    {
                        pyth[i].polygon.setMap(null);
                        pyth[i].marker.setMap(null);
                    }
                    if(control==true) {return 0;}
                }
            }
        });
    });
    //拖拽加载
    qq.maps.event.addListener(map,'dragend',function(){
        control=true;
        if(this.getZoom()>=17)
        {
            //获取经纬度范围参数
            var bs = map.getBounds();//获取可视区域
            var bssw = bs.getSouthWest();//可视区域左下角
            var bsne = bs.getNorthEast();//可视区域右上角
            var topLat = bsne.lat;
            var bottomLat = bssw.lat;
            var leftLng = bssw.lng;
            var rightLng = bsne.lng;
            $.ajax({
                type:'POST',
                url:'./admin/changeLoadIcon.php',
                data:{
                    topLat:topLat,bottomLat:bottomLat,leftLng:leftLng,rightLng:rightLng,url:'loadChange'
                },
                success:function(data)
                {
                    if(data){
                        data=eval('('+data+')');
                        for(var i=0;i<data.length;i++){
                            var type=data[i][0];
                            var number=parseInt(data[i][4]);
                            pyth[number].thebool=1;
                            createIcon(pyth,map,number,data[i][5],data[i][6],data[i][1],data[i][2],0,data[i][7],data[i][3],type);
                        }
                    }
                }
            });
            control=false;
        }
        else{
            $('svg').hide();
            $("div[title*='目标图标']").hide();
        }
    });
    //将文件数据写入地图
    function readinto(){
        count+=sum+1;
        for(var i=0;i<count;i++){
            pyth[i] = new Object();
            pyth[i].polygon=0;
        }
    }

    /*function readinto(){
        for(var i=0;i<obj.length;i++){
            pyth[i] = new Object();
            pyth[i].thebool=1;
            var type=obj[i][0];
            createIcon(pyth,map,i,obj[i][5],obj[i][6],obj[i][1],obj[i][2],0,obj[i][7],obj[i][3],type);
            count++;
        }
    }*/
    //点击按钮设置地图中心点
    $("#btn2").click(function(){
        codeAddress();
    });
    //将地图数据存入数据库
    $("input[name='save']").click(function(){
         writeInto();
    });

}
//写入实现步骤
function writeInto(){
    var row=new Array();
    var j=0;
    for(var i=sum+1;i<count;i++){
        row[j] = new Object();
        row[j].thetype=pyth[i].typeof;
        row[j].lng=pyth[i].num1;
        row[j].lat=pyth[i].num2;
        row[j].color=pyth[i].color;
        row[j].scole=pyth[i].scole1+pyth[i].scole2;
        row[j].length=pyth[i].tlength;
        row[j].width=pyth[i].twidth;
        row[j++].isDel=pyth[i].isDel;
    }
    var rowObj=JSON.stringify(row);
    $.ajax({
        url: "./admin/adminController.php",
        type: "POST",
        async:true,
        data: {rowObj:rowObj},
        //dataType:'json',
        error:function(){
            alert("数据请求失败");
        },
        success:function(data){
            alert(data);
        },
    });
}
//根据索引值删除数组中指定的数据
function del(index, dataArray){
    var thelen=dataArray.length;
    for(var i=0;i<thelen;i=i+1){
        if(i==(index-1)){
            for(var j=i+1;j<thelen;j=j+1){
                //当前索引值后的数据都向前移
                dataArray[j-1]=dataArray[j];
            }
            //移完之后,自身长度减1
            dataArray.length--;
        }
    }
}
//根据角度计算坐标,以中心点为原点
//创建矩形的实现方法,经度  维度  长  宽
function createIcon(pyth,map,count,lat,Lng,tlength,twidth,scole1,scole2,color,type){
    pyth[count].typeof=type;
    pyth[count].color=color;
    pyth[count].num1 = lat;    //经度
    pyth[count].num2 = Lng;    //Z
    pyth[count].tlength = tlength;
    pyth[count].twidth = twidth;
    var start=new qq.maps.LatLng(pyth[count].num2, pyth[count].num1);
    var end=new qq.maps.LatLng(pyth[count].num2/1.0+1, pyth[count].num1);

    var start2=new qq.maps.LatLng(pyth[count].num2, pyth[count].num1);
    var end2=new qq.maps.LatLng(pyth[count].num2, pyth[count].num1/1.0+1);
    pyth[count].num1_1  = pyth[count].tlength / getDistance(start2,end2);        //经度
    pyth[count].num2_1 = pyth[count].twidth / getDistance(start,end);          //纬度

    pyth[count].num1_2 = pyth[count].tlength*(-1) / getDistance(start2,end2);        //经度
    pyth[count].num2_2= pyth[count].twidth / getDistance(start,end);          //纬度
    pyth[count].path = [
        new qq.maps.LatLng(pyth[count].num2 / 1.0 + pyth[count].num2_1, pyth[count].num1 / 1.0 + pyth[count].num1_1),
        new qq.maps.LatLng(pyth[count].num2 / 1.0 + pyth[count].num2_2, pyth[count].num1 / 1.0 + pyth[count].num1_2),
        new qq.maps.LatLng(pyth[count].num2 / 1.0 - pyth[count].num2_1, pyth[count].num1 / 1.0 - pyth[count].num1_1),
        new qq.maps.LatLng(pyth[count].num2 / 1.0 - pyth[count].num2_2, pyth[count].num1 / 1.0 - pyth[count].num1_2),
    ];
    pyth[count].scole1=scole1;
    pyth[count].scole2=scole2;

    if(pyth[count].thebool!=1){
        pyth[count].poclick=scole(pyth,count,pyth[count].scole1,pyth[count].scole2);
        return;
    }
    pyth[count].thebool=0;
    pyth[count].polygon = new qq.maps.Polygon({
        path: pyth[count].path,
        strokeColor: color,
        strokeWeight: 1,
        fillColor: color,
        map: map,
    });
    pyth[count].marker = new qq.maps.Marker({
        position: new qq.maps.LatLng(pyth[count].num2, pyth[count].num1),
        map: map,
        draggable: true,
        icon: new soso.maps.MarkerImage("img/theicon.jpg"),
        size : new qq.maps.Size(42, 68),
        visible: true,
        title: "这是" + count + "号目标图标",
    });

    pyth[count].poclick=scole(pyth,count,pyth[count].scole1,pyth[count].scole2);
    pyth[count].marker.setCursor("move");
    pyth[count].count=count;
    
    //图标事件
    pyth[count].event=qq.maps.event.addListener(pyth[count].marker, 'position_changed', function () {
        var num3 = pyth[count].marker.getPosition();
        pyth[count].num2 = num3.getLat();
        pyth[count].num1 = num3.getLng();
        pyth[count].path = [
            new qq.maps.LatLng(pyth[count].num2 / 1.0 + pyth[count].num2_1, pyth[count].num1 / 1.0 + pyth[count].num1_1),
            new qq.maps.LatLng(pyth[count].num2 / 1.0 + pyth[count].num2_2, pyth[count].num1 / 1.0 + pyth[count].num1_2),
            new qq.maps.LatLng(pyth[count].num2 / 1.0 - pyth[count].num2_1, pyth[count].num1 / 1.0 - pyth[count].num1_1),
            new qq.maps.LatLng(pyth[count].num2 / 1.0 - pyth[count].num2_2, pyth[count].num1 / 1.0 - pyth[count].num1_2),
        ];
        pyth[count].polygon.setPath(pyth[count].path);
        $("input[name='tnumber1']").val(pyth[count].num1.toFixed(5));         //经度
        $("input[name='tnumber2']").val(pyth[count].num2.toFixed(5));         //纬度*/
        $.ajax({
            type:'POST',
            url:'./admin/changeLoadIcon.php',
            data:{
                url:'updateLocation',
                number:count,
                lng:pyth[count].num1,
                lat:pyth[count].num2,
            },
            beforeSend:function () {
                //alert("begin");
            },
            error:function()
            {
                alert("未知错误");
            },
            success:function(data)
            {
                //alert(data);
            }
        });

    });
    //单击事件-编辑属性
    pyth[count].rightcl=qq.maps.event.addListener(pyth[count].marker,'click',function(){
        $("input[name='tnumber5']").val(pyth[count].count);
        update1=pyth[count].count;
        $("#delete").show();
        $("#color").css('background-color',pyth[count].color);
        $("input[name='tlength']").val(pyth[count].tlength);
        $("input[name='twidth']").val(pyth[count].twidth);
        $("input[name='tnumber1']").val(pyth[count].num1);
        $("input[name='tnumber2']").val(pyth[count].num2);
        $("#polyType").val(pyth[count].typeof);
    });
    pyth[count].isDel=0;
}

//旋转方法
function scole(pyth,count,a,b) {
    var r=Math.sqrt(pyth[count].tlength*pyth[count].tlength+pyth[count].twidth*pyth[count].twidth)/2.0;
    var c=Math.atan(pyth[count].twidth/pyth[count].tlength);
    var arr=getLocation(a,b,r,c);
    var num3 = pyth[count].marker.getPosition();
    pyth[count].num2 = num3.getLat();
    pyth[count].num1 = num3.getLng();

    var start=new qq.maps.LatLng(pyth[count].num2, pyth[count].num1);
    var end=new qq.maps.LatLng(pyth[count].num2/1.0+1, pyth[count].num1);
    var start2=new qq.maps.LatLng(pyth[count].num2, pyth[count].num1);
    var end2=new qq.maps.LatLng(pyth[count].num2, pyth[count].num1/1.0+1);
    pyth[count].num1_1 = arr[0] / getDistance(start2,end2)*2;        //经度
    pyth[count].num2_1 = arr[1] / getDistance(start,end)*2;          //纬度

    var arr2=getLocation(a,b,r,Math.PI-c);
    pyth[count].num1_2 = arr2[0] / getDistance(start2,end2)*2;        //经度
    pyth[count].num2_2 = arr2[1] / getDistance(start,end)*2;          //纬度

    pyth[count].path = [
        new qq.maps.LatLng(pyth[count].num2 / 1.0 + pyth[count].num2_1, pyth[count].num1 / 1.0 + pyth[count].num1_1),
        new qq.maps.LatLng(pyth[count].num2 / 1.0 + pyth[count].num2_2, pyth[count].num1 / 1.0 + pyth[count].num1_2),
        new qq.maps.LatLng(pyth[count].num2 / 1.0 - pyth[count].num2_1, pyth[count].num1 / 1.0 - pyth[count].num1_1),
        new qq.maps.LatLng(pyth[count].num2 / 1.0 - pyth[count].num2_2, pyth[count].num1 / 1.0 - pyth[count].num1_2),
    ];
    pyth[count].marker.setRotation(-(a+b));
    pyth[count].polygon.setPath(pyth[count].path);
}
//a旋转角度;b初始角度;r旋转半径 ;c定点与x轴之间的夹角
function getLocation(a,b,r,c){
    var x=r*Math.cos(c);            //经度
    var y=r*Math.sin(c);            //纬度
    x0= x*Math.cos((a+b)*Math.PI/180) - y*Math.sin((a+b)*Math.PI/180) ;    
    y0= x*Math.sin((a+b)*Math.PI/180) + y*Math.cos((a+b)*Math.PI/180) ;
    var arr=new Array(2);
    arr[0]=x0;
    arr[1]=y0;
    return arr;
}
//根据经度获取两点之间的距离的2倍
function getDistance(start,end){
    var lat1 = (Math.PI/180)*start.getLat();
    var lat2 = (Math.PI/180)*end.getLat();
    var lon1 = (Math.PI/180)*start.getLng();
    var lon2 = (Math.PI/180)*end.getLng();
    //地球半径  
    var R = 6371;
    //两点间距离 km，如果想要米的话，结果*1000就可以了  
    var d =  Math.acos(Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1))*R;
    return d*1000*2;
}
//位置搜索服务实现方法
function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.getLocation(address);
}